package com.xl.basic.config;

import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import com.xl.basic.entity.ResultException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局的异常处理
 *
 * @author 钟勇
 * Create in 2023/8/17 16:46
 */
@ControllerAdvice
public class ExceptionHandleConfig {

    /**
     * 带有code和message的自定义异常
     *
     * @param e   e
     * @param <T> T
     * @return result
     */
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ExceptionHandler(ResultException.class)
    @ResponseBody
    public <T> Result<T> resultExceptionHandle(ResultException e) {
        return new Result<>(e.getCode(), e.getMessage());
    }

    /**
     * 验证器抛出的异常
     *
     * @param e   e
     * @param <T> t
     * @return result
     */
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public <T> Result<T> exceptionHandler(BindException e) {
        String msg = "参数异常";
        if (e.getFieldError() != null) {
            msg = e.getFieldError().getDefaultMessage();
        }
        return ResultEnums.ParamError.getResult(msg);
    }

    /**
     * 兜底的异常处理
     *
     * @param e   e
     * @param <T> T
     * @return result
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public <T> Result<T> exceptionHandle(Exception e) {
        return ResultEnums.Exception.getResult(e.toString());
    }
}
